import {Box, Button, Container, Divider, Grid, Pagination, Paper, Popover, ThemeProvider} from "@mui/material";
import MusicCard from "../MusicCard/MusicCard";
import React, {useEffect} from "react";
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import {createTheme} from "@mui/material/styles";
import {get163Catlist, get163CatPlayList} from '../../utils/request/163request'
import {getQCatList, getQCatPlayList} from "../../utils/request/qrequest";
import Loading from "../Loading/Loading";
import PubSub from "pubsub-js";

const theme = createTheme({
    palette: {
        primary: {
            main: 'rgba(255,255,255,0)',
            contrastText: 'black',
            light: 'rgba(255,255,255,0)'
        },
    },
});
export default function PlayListPage(props){
    let [alignment, setAlignment] = React.useState('163');

    const handleAlignment = (event, newAlignment) => {
        setAlignment(newAlignment);
        alignment = newAlignment;
        setLoading(true)
        init().then(() => {
         setLoading(false);
        }).catch(() => {
            setLoading(false)
        });
    };
    const [anchorEl, setAnchorEl] = React.useState(null);
    const [catlist, setCatlist] = React.useState([]);
    const [cat, setCat] = React.useState("全部");
    let [page, setPage] = React.useState(1);
    const [playlist, setPlaylist] = React.useState([]);
    const [pageCount, setPageCount] = React.useState(0);
    const [perPage, setPerPage] = React.useState(16);
    const [loading, setLoading] = React.useState(false);


    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };
    useEffect(async () => {
        PubSub.publish("changeTopBarByUrl",'2');
        setLoading(true);
        await init().catch(() => {
            setLoading(false)
        })
        setLoading(false)

    },[])

    async function init(){
        if(alignment === '163'){
            await get163Catlist((r) => {
                setCatlist(r);
            })
            await get163CatPlayList('全部',0,perPage,(r) => {
                setPlaylist(r.v)
                let count = r.count%perPage > 0 ? Math.floor(r.count/perPage) + 1 : r.count/perPage ;
                setPageCount(count)
                initPaginution();
            })
        }else {
            await getQCatList((r) => {
                setCatlist(r);

            })
            await getQCatPlayList('10000000',1,perPage,(r) => {
                setPlaylist(r.v)
                let count = r.count%perPage > 0 ? Math.floor(r.count/perPage) + 1 : r.count/perPage ;
                setPageCount(count)
                initPaginution();
            })
        }
    }
    function initPaginution(){
        setPage(1);
    }
    function handleChangeCatN(e){
        let cat = e.target.innerText;
        setCat(cat);
        setLoading(true);
        get163CatPlayList(cat,0,perPage,(r) => {
            setPlaylist(r.v)
            let count = r.count%perPage > 0 ? Math.floor(r.count/perPage) + 1 : r.count/perPage ;
            setPageCount(count)
            initPaginution();
            setLoading(false);
        })
    }
    function handleChangeCatQ(e){
        let cat = e.target.value;
        setCat(cat);
        setLoading(true);
        getQCatPlayList(cat,1,perPage,(r) => {
            setPlaylist(r.v)
            let count = r.count%perPage > 0 ? Math.floor(r.count/perPage) + 1 : r.count/perPage ;
            setPageCount(count)
            initPaginution();
            setLoading(false);
        })
    }
    function searchPlayList(){
        if(alignment === '163'){
            get163CatPlayList(cat,(page-1)*perPage,perPage,(r) => {
                setPlaylist(r.v)
                setLoading(false);
            }).catch(() => {
                setLoading(false)
            })
        }else if(alignment === 'qq'){
            //console.log(page)
            getQCatPlayList(cat,page,perPage,(r) => {
                setPlaylist(r.v)
                setLoading(false);
            }).catch(() => {
                setLoading(false)
            })
        }
    }

    const open = Boolean(anchorEl);
    const id = open ? 'simple-popover' : undefined;
    function NeteaseCard(){
        return(
            <Grid
                container
                direction="row"
                justifyContent="left"
                alignItems="flex-center"
            >
                <ThemeProvider theme={theme}>
                    <Button sx={{marginLeft:3}} color={"primary"} aria-describedby={id} variant="contained" onClick={handleClick}>
                        分类 >
                    </Button>
                </ThemeProvider>
                <Popover
                    id={id}
                    open={open}
                    anchorEl={anchorEl}
                    onClose={handleClose}
                    anchorOrigin={{
                        vertical: 'bottom',
                        horizontal: 'left',
                    }}
                    sx={{maxWidth:1000}}
                >
                    <Grid container
                          justifyContent="center"
                          alignItems="flex-center"
                          item xs={12}

                    >
                        <Divider light />
                        {catlist.map((r) => {

                            return (
                                <Grid container direction='row' >
                                    <Grid item xs={2} marginLeft={1}>
                                        {r.name}
                                    </Grid>
                                    <Grid item xs={8} marginTop={1} marginBottom={1}>
                                        {r.v.map((r) => {
                                            return (
                                                <ThemeProvider key={r + 't'} theme={theme}>
                                                    <Button color={"primary"} key={r} variant="contained" onClick={handleChangeCatN}>
                                                        {r}
                                                    </Button>
                                                </ThemeProvider>
                                            )
                                        })}
                                    </Grid>
                                    <Divider light />
                                </Grid>
                            )
                        })}



                    </Grid>
                </Popover>
            </Grid>
        )
    }
    function QQCard(){
        return(
            <Grid
                container
                direction="row"
                justifyContent="left"
                alignItems="flex-center"
            >
                <ThemeProvider theme={theme}>
                    <Button sx={{marginLeft:3}} color={"primary"} aria-describedby={id} variant="contained" onClick={handleClick}>
                        分类 >
                    </Button>
                </ThemeProvider>
                <Popover
                    id={id}
                    open={open}
                    anchorEl={anchorEl}
                    onClose={handleClose}
                    anchorOrigin={{
                        vertical: 'bottom',
                        horizontal: 'left',
                    }}
                    sx={{maxWidth:1000}}
                >
                    <Grid container
                          justifyContent="center"
                          alignItems="flex-center"
                          item xs={12}

                    >
                        <Divider light />
                        {catlist.map((r) => {

                            return (
                                <Grid container direction='row' >
                                    <Grid item xs={2} marginLeft={1}>
                                        {r.name}
                                    </Grid>
                                    <Grid item xs={8} marginTop={1} marginBottom={1}>
                                        {r.v.map((r) => {
                                            return (
                                                <ThemeProvider key={r.id + 't'} theme={theme}>
                                                    <Button color={"primary"} key={r.id} value={r.id} variant="contained" onClick={handleChangeCatQ}>
                                                        {r.name}
                                                    </Button>
                                                </ThemeProvider>
                                            )
                                        })}
                                    </Grid>
                                    <Divider light />
                                </Grid>
                            )
                        })}



                    </Grid>
                </Popover>
            </Grid>
        )
    }
    const handleChange = (event, value) => {
        page = value;
        setPage(value);
        setLoading(true);
        searchPlayList();
    };

    return(
        <Container maxWidth="xl">
            <Paper className='page' elevation={3}>
                <Loading open={loading}/>
                <Grid
                    container
                    direction="row"
                    justifyContent="center"
                    alignItems="flex-center"
                >
                    <Box sx={{ p: 3 }} />
                    <Grid container direction='row' justifyContent='right'>
                        <ToggleButtonGroup
                            value={alignment}
                            exclusive
                            onChange={handleAlignment}
                            aria-label="text alignment"
                            sx={{marginRight:10}}
                        >
                            <ToggleButton value="163" aria-label="网易云音乐">
                                <img src='./png163.png' width={32} height={32}/>
                            </ToggleButton>
                            <ToggleButton value="qq" aria-label="qq音乐">
                                <img src='./icoqq.png' width={32} height={32}/>
                            </ToggleButton>
                        </ToggleButtonGroup>
                    </Grid>
                    {alignment === '163' ? NeteaseCard():QQCard()}


                    <Grid container direction='row' justifyContent='center' item xs={12}>

                        {playlist.map((r) => {

                            return(
                                <MusicCard {...r} key={r.id} allList={playlist}/>
                            )

                        })}

                    </Grid>
                    <Pagination count={pageCount} onChange={handleChange} page={page} sx={{marginTop:2}}/>

                    <Box sx={{p:6}}></Box>
                </Grid>
            </Paper>

        </Container>
    )

}